import SvgaBg from '@/assets/bing.jpg'
import Kang from '@/assets/home-1.png'
import Title from '@/assets/home-3.png'
import LogoDark from '@/assets/logo-dark.png'
import OTC from '@/assets/otc.png'
import { PreLoadImages } from '@/utils'
import { XyzTransitionGroup } from '@animxyz/react'
import classNames from 'classnames'
import { useEffect, useState } from 'react'
import { Toast } from 'react-vant'
import { Parser, Player } from 'svga'
import { history, useSearchParams } from 'umi'

import styles from './index.module.less'
import '@animxyz/core'

const PLAYER_FILL_MODE = {
  // 播放完成后停在首帧
  FORWARDS: 'forwards',
  // 播放完成后停在尾帧
  BACKWARDS: 'backwards',
}

async function initSvga(params: { onEnd: () => void, onSui: () => void }) {
  const parser = new Parser()
  const [svga1, svga2] = await Promise.all([
    await parser.load('/welcome1.svga?v=1.0.2'),
    await parser.load('/welcome2.svga?v=1.0.2'),
  ])

  const player1 = new Player({
    container: document.getElementById('welcome1') as HTMLCanvasElement,
    loop: 1,
    fillMode: PLAYER_FILL_MODE.BACKWARDS as any,
  })
  const player2 = new Player({
    container: document.getElementById('welcome2') as HTMLCanvasElement,
    loop: 1,
    fillMode: PLAYER_FILL_MODE.BACKWARDS as any,
  })

  await Promise.all([player1.mount(svga1), player2.mount(svga2)])
  player1.start()
  player1.onProcess = () => {
    if (player1.currentFrame >= 48)
      player1.pause()
  }
  setTimeout(() => {
    params.onSui() // 通知外部， 冰块已碎
    player2.start()
  }, 2000)

  player2.onEnd = () => {
    player1.destroy()
    player2.destroy()
    params.onEnd()
  }

  return Promise.resolve()
}

export default function HomePage() {
  const [searchParams] = useSearchParams()
  const ignore = searchParams.get('ignore')

  const [loading, setloading] = useState<boolean>(!ignore)

  // 记录冰块碎裂之后
  const [isSui, setSui] = useState<boolean>(false)

  useEffect(() => {
    Toast.loading({
      message: '资源加载中...',
      duration: 0,
    })

    initSvga({
      onEnd() {
        setloading(false)
        setTimeout(() => {
          history.push('/draw')
        }, 2000)
      },

      // ?表示冰块碎了.
      onSui() {
        setSui(true)
      },
    }).then(() => {
      PreLoadImages() // 偷偷加载后面的图片
      Toast.clear()
    })
  }, [])

  return (
    <>
      {loading && (
        <div className="fixed top-0 left-0 z-20 w-screen h-screen">
          {!isSui && (
            <i
              className=" block w-full h-full absolute left-0 top-0 bg-cover bg-no-repeat bg-center bg-[#b4d7f3]"
              style={{
                backgroundImage: `url(${SvgaBg})`,
              }}
            >
            </i>
          )}
          <canvas
            id="welcome2"
            className="block object-cover absolute top-0 left-0 w-full h-full"
          >
          </canvas>
          <canvas
            id="welcome1"
            className=" absolute left-0 top-0 block w-full h-[1370px] scale-90 object-cover"
          >
          </canvas>
        </div>
      )}

      <XyzTransitionGroup
        duration="auto"
        appear
        appearVisible
        xyz="fade"
        className={classNames(
          'min-h-screen bg-cover  bg-bottom bg-no-repeat flex flex-col justify-center items-center relative overflow-hidden',
          styles.pageContainer,
        )}
      >
        {!loading && (
          <i
            xyz="fade up-1"
            className="w-[450px] relative z-10 h-[144px] bg-cover bg-center"
            style={{
              backgroundImage: `url(${LogoDark})`,
            }}
          >
          </i>
        )}
        {!loading && (
          <div
            style={{
              backgroundImage: `url(${Title})`,
            }}
            xyz="fade up-1 delay-1"
            className="-mt-4 mb-6 w-[480px] h-[152px] bg-cover block relative"
          />
        )}

        {/* kang */}
        {!loading && (
          <img
            xyz="fade up-1 delay-2"
            src={Kang}
            className="block w-[650px] h-[723px] object-cover -mt-[150px] -mb-[20px]"
            alt=""
          />
        )}

      </XyzTransitionGroup>

      <img src={OTC} className=" absolute left-2 bottom-2 w-[600px] z-50" alt="" />
    </>
  )
}
